"""


"""
from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template


@index_blu.route("/")
@user_login_data
def index():

    # 进入首页的时候 获取用户登录信息
    user = g.user

    # 查询新闻数据(实现点击排行新闻数据展示的功能)
    try:
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 首页分类的展示(首页导航)
    try:
        news_category = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)




    # 返回数据到模板中
    data={
        "user_info": user.to_dict() if user else None,
        "news_click": news_click,
        "news_category": news_category
    }

    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def get_web_icon():
    """处理窗口小图标的请求"""
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route("/news_list")
def news_list():
    """
    处理 首页新闻列表数据的 请求


    1, 获取参数判空
    2,查询数据库, News    排序查询(按时间排序)  分页查询
    3,返回数据到前端
    """
    # 1, 获取参数判空

    data_dict = request.args
    page = data_dict.get("page", 1)   # 当前请求第几页
    cid = data_dict.get("cid", 1)   # 当前请求的新闻分类
    per_page = data_dict.get("per_page", 5)  # 每页多少条数据
    if not all([page, cid, per_page]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2,查询数据库, News    排序查询(按时间排序)  分页查询
    filters = [News.status == 0]   # 条件列表,专门存放查询条件
    if cid != 1:
        filters.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        items = paginate.items  # 当前页的数据 [<>,<>,<>]
        currentPage = paginate.page
        totalPage = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    # 因为js不认识python对象,要把items里面的数据转换成字典,而不是python对象
    newsList = []
    for i in items:
        newsList.append(i.to_basic_dict())

    # 3,返回数据到前端
    return jsonify(errno=RET.OK, errmsg="OK", newsList=newsList, totalPage=totalPage, currentPage=currentPage)






